package com.zp.crm.Controller.PubController;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.gson.Gson;
import com.zp.crm.entity.Pub.PubEntity;
import com.zp.crm.service.PubService.PubService;

@Controller
@RequestMapping("/pub")
public class PubController {
	
	@Resource
	public PubService pubService;
	/*
	 * 查询操作，可有条件查询，可无条件查询，输出的为Html形式
	 * */
	@RequestMapping(value="/select",method=RequestMethod.POST)
	public void Select(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/htm;charset=utf-8");
		String pagesrt=request.getParameter("page");
		String code=request.getParameter("code");
		String name=request.getParameter("name");
		int page=1,size=10;
		if(pagesrt != null){
			page=Integer.parseInt(pagesrt);
		}
		Map<String, Object> map=pubService.select(code,name,page,size);
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("message"));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * 添加操作
	 * */
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public void insert(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		response.setContentType("text/htm;charset=utf-8");
		String code=request.getParameter("code");
		String name=request.getParameter("name");
		String reqpath="";
		String fileName="";
    	String attachmentName="";
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
        	 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
            	fileName="";
            	attachmentName="";
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        System.out.println(myFileName);
                        myFileName=myFileName.split("\\.")[myFileName.split("\\.").length-1];
                        System.out.println(myFileName);
                        if(myFileName.equals("jpg")||myFileName.equals("png")||myFileName.equals("gif")){
                        	//重命名上传后的文件名  
                        	fileName = UUID.randomUUID().toString()+"."+ myFileName;  
                    		String basePath =getClass().getResource("../../../../../../../").getFile().toString();  
                    		basePath=basePath.substring(1);
                            //定义上传路径  
                            String path = basePath+"/img/" + fileName;  
                            File localFile = new File(path);  
                            file.transferTo(localFile);  
                        	
                        }else{
                        	//重命名上传后的文件名  
                        	attachmentName = UUID.randomUUID().toString()+":"+myFileName;  
                    		String basePath =getClass().getResource("../../../../../../../").getFile().toString();  
                    		basePath=basePath.substring(1);
                            //定义上传路径  
                            String path = basePath+"/text/" + attachmentName;  
                            File localFile = new File(path);  
                            file.transferTo(localFile);  
                        }
                   }
                }  
             } 
         }
		if(fileName.equals("")){
			reqpath=null;
		}else{
			reqpath=fileName;
		}
		
		PubEntity entity=new PubEntity(code, name, reqpath);
		
		Map<String, Object> map=pubService.insert(entity);
		
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("success"));
		}catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/*
	 * 修改操作
	 * */
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public void edit(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		response.setContentType("text/htm;charset=utf-8");
		String idStr=request.getParameter("id");
		String code=request.getParameter("code");
		String name=request.getParameter("name");
		int id=0;
		if(idStr !=null){
			id=Integer.parseInt(idStr);
		}
		String reqpath="";
		String fileName="";
    	String attachmentName="";
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
        	 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
            	fileName="";
            	attachmentName="";
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        System.out.println(myFileName);
                        myFileName=myFileName.split("\\.")[myFileName.split("\\.").length-1];
                        System.out.println(myFileName);
                        if(myFileName.equals("jpg")||myFileName.equals("png")||myFileName.equals("gif")){
                        	//重命名上传后的文件名  
                        	fileName = UUID.randomUUID().toString()+"."+ myFileName;  
                    		String basePath =getClass().getResource("../../../../../../../").getFile().toString();  
                    		basePath=basePath.substring(1);
                            //定义上传路径  
                            String path = basePath+"/img/" + fileName;  
                            File localFile = new File(path);  
                            file.transferTo(localFile);  
                        	
                        }else{
                        	//重命名上传后的文件名  
                        	attachmentName = UUID.randomUUID().toString()+":"+myFileName;  
                    		String basePath =getClass().getResource("../../../../../../../").getFile().toString();  
                    		basePath=basePath.substring(1);
                            //定义上传路径  
                            String path = basePath+"/text/" + attachmentName;  
                            File localFile = new File(path);  
                            file.transferTo(localFile);  
                        }
                   }
                }  
             } 
         }
		if(fileName.equals("")){
			reqpath=null;
		}else{
			reqpath=fileName;
		}
		
		PubEntity entity=new PubEntity(id,code, name,reqpath);
		
		Map<String, Object> map=pubService.edit(entity);
		
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("success"));
		}catch (Exception e) {
			e.printStackTrace();
		}

	}
	/*
	 *删除操作
	 * */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public void Delete(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/htm;charset=utf-8");
		String idstr=request.getParameter("id");
		int id=0;
		if(idstr != null){
			id=Integer.parseInt(idstr);
		}
		Map<String, Object> map=pubService.delete(id);
		
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("success"));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * 根据类型查询并转换成下拉列表形式
	 * */
	@RequestMapping(value="/selectcode",method=RequestMethod.POST)
	public void SelectCode(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/htm;charset=utf-8");
		String code=request.getParameter("code");
		Map<String, Object> map=pubService.SelectCode(code);
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("message"));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/gr",method=RequestMethod.POST)
	public void GroySelect(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/htm;charset=utf-8");
		String type=request.getParameter("type");
		String from=request.getParameter("from");
		Map<String, Object> map=pubService.SelectGy(type,from);
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("message"));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/yz",method=RequestMethod.POST)
	public void SelectByTypeNameYz(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/htm;charset=utf-8");
		String type=request.getParameter("type");
		String name=request.getParameter("name");
		Map<String, Object> map=pubService.SelectByTypeNameYz(type,name);
		try{
			PrintWriter out=response.getWriter();
			out.println(map.get("success"));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/selectById",method=RequestMethod.POST)
	public void SelectById(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/htm;charset=utf-8");
		String idStr=request.getParameter("id");
		int id=0;
		if(idStr != null){
			id=Integer.parseInt(idStr);
		}
		Map<String, Object> map=pubService.SelectById(id);
		try{
			PrintWriter out=response.getWriter();
			String json=new Gson().toJson(map);
			out.println(json);
		}catch (Exception e) {
			e.printStackTrace();
		}

	}
}
